package com.tengju.bff.interfaces.shared;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

public class DateTimeAssembler {

    private static final DateTimeFormatter DATE_TILL_DAY_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATE_TILL_SECOND_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private DateTimeAssembler() {
    }

    public static LocalDateTime daysAgo(int minusDays ){
        return LocalDateTime.now().minusDays(minusDays);
    }

    /**
     * 获取指定日期的 天前
     *
     * @param dateTime  日期时间
     * @param minusDays -天
     * @return {@link LocalDateTime}
     */
    public static LocalDateTime daysAgo(LocalDateTime dateTime, int minusDays ){
        return dateTime.minusDays(minusDays);
    }


    public static String formatDateTillDay(LocalDateTime time){
        return Optional.ofNullable(time)
                .map(t -> time.format(DATE_TILL_DAY_FORMATTER))
                .orElse("");
    }

    public static String formatDateTillSecond(LocalDateTime time){
        return Optional.ofNullable(time)
                .map(t -> time.format(DATE_TILL_SECOND_FORMATTER))
                .orElse("");
    }

    public static LocalDateTime parseDateTillSecond(String time){
        return Optional.ofNullable(time)
                .filter(StringUtils::isNotEmpty)
                .map(t -> LocalDateTime.parse(time, DATE_TILL_SECOND_FORMATTER))
                .orElse(null);
    }

    public static LocalDateTime parseDateTillDay(String time){
        return Optional.ofNullable(time)
                .filter(StringUtils::isNotEmpty)
                .map(t -> LocalDate.parse(time, DATE_TILL_DAY_FORMATTER).atStartOfDay())
                .orElse(null);
    }
}
